package com.archive.cleaner.util;

import com.archive.cleaner.config.DbCleanerConfig;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.introspector.PropertyUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CleanerUtil {

    public static DbCleanerConfig parseConfig(String configFile) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(configFile));
        String content = new String(bytes, StandardCharsets.UTF_8);

        Pattern pattern = Pattern.compile("-([a-z])");
        Matcher matcher = pattern.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String group = matcher.group();
            matcher.appendReplacement(sb, group.substring(1).toUpperCase());
        }
        matcher.appendTail(sb);

        return createYaml().loadAs(sb.toString(), DbCleanerConfig.class);
    }

    private static Yaml createYaml() {
        LoaderOptions loaderOptions = new LoaderOptions();
        loaderOptions.setAllowDuplicateKeys(false);
        loaderOptions.setMaxAliasesForCollections(Integer.MAX_VALUE);
        loaderOptions.setAllowRecursiveKeys(true);
        Constructor constructor = new Constructor(DbCleanerConfig.class, loaderOptions);

        PropertyUtils propertyUtils = new PropertyUtils();
        propertyUtils.setSkipMissingProperties(true);
        constructor.setPropertyUtils(propertyUtils);

        return new Yaml(constructor);
    }

}